package com.supermap.wzhy.module.user.api;

import com.supermap.wzhy.common.annotation.MethodName;
import com.supermap.wzhy.common.annotation.Permission;
import com.supermap.wzhy.common.annotation.Role;
import com.supermap.wzhy.common.api.BaseController;
import com.supermap.wzhy.data.OpStatus;
import com.supermap.wzhy.data.PageInfo;
import com.supermap.wzhy.entity.TUserpower;
import com.supermap.wzhy.entity.TUserrole;
import com.supermap.wzhy.entity.TUsers;
import com.supermap.wzhy.module.user.service.PowerService;
import com.supermap.wzhy.module.user.service.RolePowerRelationService;
import com.supermap.wzhy.module.user.service.UserRoleService;
import com.supermap.wzhy.module.user.service.UserService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * Created by W.Qiong on 14-2-27.
 * 用户角色
 * Added by Linhao on 14-09-17
 */
@Controller
@RequestMapping(value = {"/roles","/service/roles"})
public class UserRoleController extends BaseController{
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    UserService userService;
    @Autowired
    PowerService powerService;
    @Autowired
    RolePowerRelationService rolePowerRelationService;


    @RequestMapping(value = "",method = RequestMethod.POST)
    public  @ResponseBody OpStatus createUserRole(TUserrole role){
        boolean re = userRoleService.create(role);
        return  getOpStatus(re);
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public  @ResponseBody TUserrole getUserRole(@PathVariable int id){
        return  userRoleService.one(id);
    }

    @RequestMapping(value = "",method = RequestMethod.GET)
    public  @ResponseBody
    Page<TUserrole> getAllUserRole(TUserrole role,PageInfo page ){
        return  userRoleService.query(role, getPageRequest(page));
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.PUT)
    public  @ResponseBody OpStatus updateUserRole(@PathVariable int id,TUserrole role ){
        boolean re =  userRoleService.update(id,role);
        return  getOpStatus(re);
    }

    /**
     * 删除指定角色时，判断当前角色是否被用户使用,被使用不可删除
     *
     * @param id
     *          roleid
     * @return
     */
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    @MethodName("删除角色")
    public  @ResponseBody OpStatus deteleUserRole(@PathVariable int id){
        List<TUsers> list = userService.findByRoleid(id);
        if(list != null && list.size() > 0){
            //用户已经使用该角色，不可删除
            StringBuilder msg = new StringBuilder("删除失败！该角色已被用户");
            boolean isFirst = true;
            for (TUsers tUsers : list){
                if(isFirst){
                    isFirst = false;
                }else{
                    msg.append(",");
                }
                msg.append("[").append(tUsers.getUserCaption()).append("]");
            }
            msg.append(" 使用，禁止删除!");
            return new OpStatus(false,msg.toString(),null);
        }else{
            boolean re = userRoleService.delete(id);
            return getOpStatus(re);
        }
    }

    /**
     * 获取指定角色下的用户列表
     * @param id
     *          roleid
     * @return
     */
    @RequestMapping(value = "/{id}/users",method = RequestMethod.GET)
    public @ResponseBody List<TUsers> getUsersByRoleId(@PathVariable int id){
        return userService.findByRoleid(id);
    }

    /**
     * 获取指定父节点下的权限
     *
     * @param id
     *          指定节点作为权限id
     * @return
     */
    @RequestMapping(value = "/{id}/subRoles",method = RequestMethod.GET)
    public @ResponseBody List<TUserrole> getRolesByparid(@PathVariable("id") int id){
        return userRoleService.getRolesByparid(id);
    }


    /**
     * 列表指定角色下的所有权限
     *
     * @param id
     *          roleId
     * @return
     */
    @RequestMapping(value = "/{id}/rolepower",method = RequestMethod.GET)
    public @ResponseBody List<TUserpower> getUserpowerByRoleId(@PathVariable int id){
        return powerService.findUserpowerListByRoleid(id);
    }

    /**
     * 列表当前指定角色下的的所有权限
     * （包括子角色的权限，去掉重复的权限）
     * @param id
     *          roleId
     * @return
     */
    @RequestMapping(value = "/{id}/allrolepower",method = RequestMethod.GET)
    public @ResponseBody Map<String,Object> getAllRolepowerByRoleId(@PathVariable int id){
        return userRoleService.getAllRolepowerByRoleId(id);
    }


    /**
     * 将当前节点的下级节点的父节点改为当前节点的父节点
     *
     * @param id
     *         roleId
     * @param parid
     *         parid (删除节点的父节点id)
     * @return
     */
    @RequestMapping(value = "/{id}/movesubitem",method = RequestMethod.POST)
    public @ResponseBody OpStatus moveNextSubItemsByroleid(@PathVariable int id,
                   int parid){
        boolean re = userRoleService.moveNextSubItemsByroleid(id,parid);
        return getOpStatus(true);
    }


    /**
     * 下载导入分组值的模板
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "import/template/download",method = RequestMethod.GET)
    @ResponseBody
    public void downloadTempalte(HttpServletRequest request,HttpServletResponse response)
            throws  Exception{
        String filename = new String("角色导入模板".getBytes(),"iso8859-1");
        response.reset();
        response.setContentType("APPLICATION/vnd.ms-excel");
        //注意，如果去掉下面一行代码中的attachment; 那么也会使IE自动打开文件。
        response.setHeader("Content-Disposition", "attachment;filename="+filename+".xls");
        HSSFWorkbook wk = userRoleService.downloadTemplate();
        OutputStream out  =response.getOutputStream() ;
        wk.write(out);
        out.flush();
        out.close();
    }

    /**
     * 导入分组值数据
     *
     * @param request
     * @param path
     * @param sheetName
     * @return
     */
    @RequestMapping(value = "/import",method = RequestMethod.POST)
    @ResponseBody
    public OpStatus importRole(HttpServletRequest request,@Param("path") String path,
                                 @Param("sheetName") String sheetName){
        boolean re=  userRoleService.importRole(path,sheetName,0);

        return getOpStatus(re);
    }

    @RequestMapping(value = "/{id}/setrolepower",method = RequestMethod.POST)
    @ResponseBody
    public OpStatus setRolePowers(@PathVariable int id,@RequestBody int[] powerids){
        int count = rolePowerRelationService.setRolepower(id,powerids);
        if(count > -1){
            return getOpStatus(true);
        }else{
            return getOpStatus(false);
        }
    }

    /**
     * 获取角色树形结构
     *
     * @return
     */
    @RequestMapping(value = "/tree", method = RequestMethod.GET)
    @ResponseBody
    @Permission(Role.ADMIN)
    public Map<String,Object> getRoleTree(){
        return userRoleService.getRoleTree();
    }
}